package com.cskaoyan.utils;

import com.cskaoyan.bean.User;
import com.cskaoyan.exception.MyValidationException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.sql.Date;

import javax.servlet.http.HttpServletRequest;

/**
 * @PROJECT_NAME: market_34th
 * @DESCRIPTION:通用工具类
 * @Author: qiu
 * @DATE: 2021/10/19 10:10
 */
public class CommonUtil {

    // 判断字符串是否为空
    public static boolean isStrNotEmpty(String str){
        return (str != null && !"".equals(str.trim()));
    }
    // 设置时间
    public static Date nowTime(){ return new Date(System.currentTimeMillis()); }
    public static Integer getUserId(){
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        return primaryPrincipal.getId();
    }

    /**
     * 判断xxx是否为null或绝对空
     * @param t
     * @param <T>
     * @return
     */
    public static<T> boolean isNull(T t) {
        if (t != null && !"".equals(t)) {
            return false;
        }
        return true;
    }

    // 数据校验工具类
    public static void valid(BindingResult bindingResult) throws MyValidationException {
        if (bindingResult.hasFieldErrors()) {
            //还可以进一步的获得校验结果
            FieldError fieldError = bindingResult.getFieldError();
            //默认的信息
            String defaultMessage = fieldError.getDefaultMessage();
            throw new MyValidationException(defaultMessage);
        }
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}
